package com.microservice.auth.jwt.handler;

import cn.hutool.json.JSONUtil;
import com.microservice.core.domain.AjaxResult;
import com.microservice.core.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * AuthenticationSuccessHandler 是 Spring Security 中的一个接口，用于处理用户成功认证后的逻辑。当用户成功登录后，
 * Spring Security 会调用 AuthenticationSuccessHandler 来处理后续的操作，例如重定向到特定页面、返回JSON响应等。
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        System.out.println("原来的token:" + httpServletResponse.getHeader(JwtUtil.HEADER));
        httpServletResponse.setHeader(JwtUtil.HEADER, httpServletResponse.getHeader(JwtUtil.HEADER));
        AjaxResult ajaxResult = AjaxResult.success("SuccessLogin");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(ajaxResult).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
